# List of all parameters

lr.list = c(.05,.025,.01,.005,.001)
tc.list = c(1,3,5,10,15)
tf.list = c(.1,.25,.33,.5,.75,1)
nt.list = c(3000,5000,7000,10000)

# Directory to create sub-directories in

out.dir = '/home1/99/jc152199/brt/output/maxtemp2/'

# Directory for .sh files

tmp.pbs = '/home1/99/jc152199/tmp.pbs6/'
setwd(tmp.pbs)

# Location of script to run

script.file = paste(out.dir,'optimization.r',sep='')

i=1 # To track position in loop

for (lr in lr.list)

	{
	
	for (tc in tc.list)
	
		{
		
		for (tf in tf.list)
		
			{
			
			for (nt in nt.list)
			
				{
				
				dir.create(paste(out.dir,'p_',sprintf('%03i',i),sep=''))
				
				tname = paste('p_',sprintf('%03i',i),'.sh',sep='') # Create a name for the .sh script
	
				arg.lr = paste('lr="',lr,'" ',sep='') # Define the argument for lr
				arg.tc = paste('tc="',tc,'" ',sep='') # Define the argument for tc
				arg.tf = paste('tf="',tf,'" ',sep='') # Define the argument for tf
				arg.nt = paste('nt="',nt,'" ',sep='') # Define the argument for nt
				arg.i = paste('i="',i,'" ',sep='') # Define the argument for i
				arg.dir = paste('output.dir="',out.dir,'p_',sprintf('%03i',i),'/','" ',sep='')
	
				zz = file(tname,'w') # This command creates a file with the name 'tname' The 'w' command opens the file and writes the following lines of text into it
		
					cat('##################################\n',file=zz) # First blank line of .sh file ### Note the use of '\n', any text following this will be on the next line
					cat('#!/bin/sh\n',file=zz) # First command line for HPC
					cat('cd $PBS_O_WORKDIR\n',file=zz) # Sets the directory to write out summary files at the above directory 'tmp.pbs'
					cat("R CMD BATCH --no-save --no-restore '--args ",arg.lr,arg.tc,arg.tf,arg.nt,arg.i,arg.dir,"' ",script.file,' ',gsub('.sh','',tname),'.Rout \n',sep='',file=zz) # This line tells R not to save to the .Rdata file and also not to restore the environment from the .Rdata file, very important when batching or you will get multiple fuckups, also defines the arguments, says where script to run is located, and defines the name for the R.out file
					cat('##################################\n',file=zz) # Last blank line of .sh file
				
				close(zz) # Closes the .sh file that you've just written
	
				cat('\n',tname)
	
				# The follow line submits the job to the HPC, leave it commented out until you're ready to RUN all the jobs\
				# Always run the script first without removing the comment, this will still generate the .sh files for you to check before running
				# Once you're happy with that then submit a single .sh file and make sure it runs through to completion before batching out the rest with the following line
				
				system(paste('qsub -m n -l nodes=1:ppn=8 ',tname,sep=''))
							
				i=i+1
				
				}
				
			}
			
		}
		
	}
	
# End Loop